package com.rybbaby.tss.platform.sysCitys.controller;

import com.rybbaby.tss.core.annotation.RequestLog;
import com.rybbaby.tss.core.annotation.Token;
import com.rybbaby.tss.core.annotation.validator.RegexpValidator;
import com.rybbaby.tss.core.annotation.validator.StringValidator;
import com.rybbaby.tss.core.bean.PageBean;
import com.rybbaby.tss.core.hqlsearch.HqlGenerateUtil;
import com.rybbaby.tss.core.utils.AjaxJsonResponse;
import com.rybbaby.tss.core.utils.PropertiesReadUtil;
import com.rybbaby.tss.core.utils.SequenceUtil;
import com.rybbaby.tss.core.utils.StringUtils;
import com.rybbaby.tss.core.web.controller.BaseController;
import com.rybbaby.tss.platform.initializer.SysCityInitializer;
import com.rybbaby.tss.platform.sysCitys.entity.SysCitys;
import com.rybbaby.tss.platform.sysCitys.service.ISysCitysService;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description 全球城市管理
 * 
 * @author 谢进伟
 * 
 * @createDate 2016-11-30 下午3:21:45
 */
@Controller
@RequestMapping(value = "sysCitysController")
public class SysCitysController extends BaseController {

	@Autowired
	private ISysCitysService sysCitysService;

	/**
	 * 获取全球城市列表
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestLog(content = "获取全球城市列表" , save = true)
	@RequestMapping(value = "sysCitysList", method = RequestMethod.POST)
	public ModelAndView sysCitysList(SysCitys entity, PageBean paramPageBean) {
		ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("sysCitysListView"));
		try {
			Map<String, String[]> unLockMap = getParameterMap(request);
			DetachedCriteria dc = DetachedCriteria.forClass(SysCitys.class);
			HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
			PageBean pageBean = sysCitysService.pageList(dc, paramPageBean.getPageNo(), paramPageBean.getPageSize());
			mav.addObject(super.SEARCH_MAP, unLockMap);
			mav.addObject(super.PAGE_BEAN, pageBean);
			mav.addObject("searchFormId", SEARCH_FORM);
			mav.addObject("actionUrl", request.getRequestURI());
			mav.addObject("pagingBar", pageBean.getPagingBar(SEARCH_FORM));
			mav.addObject("serializeNum", SequenceUtil.getUpperCaseUUID());
			String requestURI = StringUtils.substringBeforeLast(request.getRequestURI(), "/");
			mav.addObject("editUrl", requestURI + "/toEditView.do");
			mav.addObject("deleteUrl", requestURI + "/delete.do");
			mav.addObject("batchDeleteUrl", requestURI + "/batchDelete.do");
		} catch (Exception e) {
			throw e;
		}
		return mav;
	}

	/**
	 * 转到编辑视图
	 * 
	 * @param entity
	 *            接收编辑参数的临时对象
	 * @param serializeNum
	 *            请求标识
	 * @return
	 */
	@RequestLog(content = "转到全球城市视图" , save = true)
	@RequestMapping(value = "toEditView", method = RequestMethod.GET)
	public ModelAndView toEditView(SysCitys entity, @RequestParam(required = true) String serializeNum) {
		ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("sysCitysEditView"));
		if (entity != null && entity.getId() != null) {
			SysCitys editEntity = this.sysCitysService.get(entity.getId());
			mav.addObject("editEntity", editEntity);
			mav.addObject("editModel", "edit");
		} else {
			mav.addObject("editModel", "add");
		}
		mav.addObject("serializeNum", serializeNum);
		mav.addObject("saveUrl", StringUtils.substringBeforeLast(request.getRequestURI(), "/") + "/saveOrUpdate.do");
		return mav;
	}

	/**
	 * 保存编辑的对象
	 * 
	 * @param entity
	 *            被编辑对象
	 * @return
	 */
	@ResponseBody
	@RequestLog(content = "保存全球城市对象" , save = true)
	@Token(validateToken = false)
	@RequestMapping(value = "saveOrUpdate", method = RequestMethod.POST)
	public String saveOrUpdate(SysCitys entity) {
		AjaxJsonResponse ajr = new AjaxJsonResponse();
		try {
			String id = entity.getId();
			ajr.setResMsg("保存成功!");
			if (StringUtils.isNotBlank(id)) {
				SysCitys destEntity = this.sysCitysService.get(id);
				BeanUtils.copyProperties(entity, destEntity);
				this.sysCitysService.updateEntitiy(destEntity);
				SysCityInitializer.loadAll();
			} else {
				Serializable newId = this.sysCitysService.save(entity);
				if (newId == null) {
					ajr.setResCode(301);
					ajr.setResMsg("保存失败!");
				}else{
					SysCityInitializer.loadAll();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			ajr.setResCode(500);
			ajr.setResMsg("保存失败(" + e.getMessage() + ")!");
		}
		return ajr.jsonResponse(false);
	}

	/**
	 * 删除指定id的对象
	 * 
	 * @param id
	 *            需要被删除的对象id
	 * @return
	 */
	@ResponseBody
	@RequestLog(content = "删除属性" , save = true)
	@RequestMapping(value = "delete", method = RequestMethod.GET)
	public String delete(@StringValidator(nullable = false) String id) {
		AjaxJsonResponse ajr = new AjaxJsonResponse();
		try {
			ajr.setResMsg("删除成功!");
			if (StringUtils.isNotBlank(id)) {
				this.sysCitysService.deleteEntityById(id);
				SysCityInitializer.loadAll();
			} else {
				ajr.setResMsg("删除失败!");
				ajr.setResCode(302);
			}
		} catch (Exception e) {
			e.printStackTrace();
			ajr.setResCode(500);
			ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
		}
		return ajr.jsonResponse(false);
	}

	/**
	 * 批量删除指定id的对象
	 * 
	 * @param ids
	 *            需要被删除的对象id组成的字符串
	 * @return
	 */
	@ResponseBody
	@RequestLog(content = "删除属性" , save = true)
	@RequestMapping(value = "batchDelete", method = RequestMethod.GET)
	public String batchDelete(@RegexpValidator(nullable = false, regexp = "^(\\w+,?)+\\w+$") String ids) {
		AjaxJsonResponse ajr = new AjaxJsonResponse();
		try {
			ajr.setResMsg("删除成功!");
			if (StringUtils.isNotBlank(ids)) {
				boolean batchDelete = this.sysCitysService.batchDelete(ids.split(","));
				if (!batchDelete) {
					ajr.setResMsg("删除失败!");
					ajr.setResCode(302);
				}else{
					SysCityInitializer.loadAll();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			ajr.setResCode(500);
			ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
		}
		return ajr.jsonResponse(false);
	}

	@ResponseBody
	@RequestLog(content = "查询省 市 区" , save = true)
	@Token(validateToken = false)
	@RequestMapping(value = "selectCity")
	public String queryCity(String preCode, String type) {
		AjaxJsonResponse ajr = new AjaxJsonResponse();
		List<SysCitys> list = null;
		DetachedCriteria dc = DetachedCriteria.forClass(SysCitys.class);
		if (StringUtils.isEmpty(type)) {
			if (preCode == null) {
				dc.add(Restrictions.eq("levelType", 1));
				list = sysCitysService.findByDetached(dc);
			} else {
				dc.add(Restrictions.eq("pId", preCode));
				list = sysCitysService.findByDetached(dc);
			}
			ajr.setData(list);
			return ajr.jsonResponse(true);
		} else {
			dc.add(Restrictions.eq("levelType", type));
			list = sysCitysService.findByDetached(dc);
			ajr.setData(list);
			return ajr.jsonResponse(true);
		}

	}


	/**
	 * 获取所有的省/直辖市列表
	 *
	 * @return
	 */
	@ResponseBody
	@RequestLog(content = "获取所有的省/直辖市" , save = true)
	@Token(validateToken = false)
	@RequestMapping(value = "provinceList",method = RequestMethod.GET)
	public String provinceList() {
		//获取所有的省/直辖市
		DetachedCriteria dc = DetachedCriteria.forClass(SysCitys.class);
		dc.add(Restrictions.eq("levelType", 1));
		List<SysCitys> data =this.sysCitysService.findByDetached(dc);
		List<Map<String,Object>> newData=new ArrayList<>();
		data.forEach((city)->{
			Map<String,Object> map=new HashMap<>();
			map.put("id",city.getId());
			map.put("name",city.getName());
			newData.add(map);
		});
		AjaxJsonResponse ajr = new AjaxJsonResponse();
		ajr.setData(newData.toArray());
		return ajr.jsonResponse(true);
}

	/**
	 * 根据父级Id获取下级城市/区/县
	 *
	 * @param pId 父级id
	 * @return
	 */
	@ResponseBody
	@RequestLog(content = "根据父级Id获取下级城市/区/县" , save = true)
	@Token(validateToken = false)
	@RequestMapping(value = "getChildrens",method = RequestMethod.GET)
	public String getChildrens(@RequestParam(required = true) String pId) {
		//根据父级Id获取下级城市/区/县
		List<SysCitys> data = this.sysCitysService.getChildrens(pId);
		List<Map<String,Object>> newData=new ArrayList<>();
		data.forEach((city)->{
			Map<String,Object> map=new HashMap<>();
			map.put("name",city.getName());
			map.put("id",city.getId());
			newData.add(map);
		});
		AjaxJsonResponse ajr = new AjaxJsonResponse();
		ajr.setData(newData.toArray());
		return ajr.jsonResponse(true);
	}
}
